<template>
	<view class="cunjiu-container">
		<!-- 吧员存酒功能 -->
		<view v-if="isBayuan" class="add-wine-section">
			<view class="section-title">新增存酒记录</view>
			<view class="form-item">
				<text class="label">业务经理/管理层:</text>
				<picker 
					mode="selector" 
					:range="businessManagers" 
					range-key="userName"
					:value="businessManagers.findIndex(item => item.userId === newWineForm.userId)"
					@change="handleNewWineManagerChange"
					class="picker"
				>
					<view class="picker-text">{{ newWineForm.userName || '请选择业务经理/管理层' }}</view>
				</picker>
			</view>
		
			<view class="form-item">
				<text class="label">房间名称:</text>
				<view class="room-search-container">
					<input 
						class="room-search-input" 
						type="text" 
						v-model="newWineForm.roomSearchText" 
						placeholder="请输入房间名称搜索" 
						@input="handleRoomSearch"
					/>
					<button class="room-search-btn" @click="searchRooms">搜索</button>
				</view>
			</view>
			<view v-if="filteredRoomList.length > 0" class="form-item">
				<text class="label">选择房间:</text>
				<picker 
					mode="selector" 
					:range="filteredRoomList" 
					range-key="cc"
					:value="filteredRoomList.findIndex(item => item.id === newWineForm.selectedRoomId)"
					@change="handleRoomNameChange"
					class="picker"
				>
					<view class="picker-text">{{ newWineForm.roomName || '请选择房间' }}</view>
				</picker>
			</view>
			<view class="form-item">
		


				<text class="label">酒名:</text>
				<picker 
					mode="selector" 
					:range="wineOptions" 
					:value="wineOptions.indexOf(newWineForm.wineName)"
					@change="handleNewWineNameChange"
					class="picker"
				>
					<view class="picker-text">{{ newWineForm.wineName || '请选择酒名' }}</view>
				</picker>
			</view>
			<view class="form-item">
				<text class="label">数量:</text>
				<input 
					class="input" 
					type="number" 
					v-model="newWineForm.quantity" 
					placeholder="请输入数量" 
				/>
			</view>
			<button class="confirm-add-btn" @click="handleAddWine" :disabled="!isNewWineFormValid">确认新增</button>
		</view>


		<!-- 业务经理/管理层存酒总数展示 -->
	<!-- 业务经理/管理层存酒总览（Inline 样式版） -->
<view
  v-if="isBusinessManager"
  style="
    background-color: #fff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
  "
>
  <!-- 标题 -->
  <view
    style="
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      text-align: center;
      margin-bottom: 20rpx;
    "
  >
    存酒总览
  </view>

  <!-- 每种酒的总数 -->
  <view
    class="total-item"
    v-for="(quantity, wineName) in totalWineQuantities"
    :key="wineName"
    style="
      display: flex;
      justify-content: space-between;
      padding: 15rpx 0;
      border-bottom: 1rpx solid #eee;
    "
  >
    <text
      style="
        font-size: 30rpx;
        color: #666;
        font-weight: bold;
      "
    >{{ wineName }}:</text>
    <text
      style="
        font-size: 30rpx;
        color: #007aff;
        font-weight: bold;
      "
    >{{ quantity }} 瓶</text>
  </view>

  <!-- 无记录提示 -->
  <view
    v-if="Object.keys(totalWineQuantities).length === 0"
    style="
      text-align: center;
      color: #999;
      font-size: 28rpx;
      padding: 20rpx 0;
    "
  >
    暂无存酒记录
  </view>
</view>

<!-- 业务经理/管理层送酒功能（Inline 样式版） -->
<view
  v-if="isBusinessManager"
  style="
    background-color: #fff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
  "
>
  <!-- 标题 -->
  <view
    style="
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      text-align: center;
      margin-bottom: 20rpx;
    "
  >
    送酒
  </view>

  <!-- 房间名称搜索 -->
  <view
    style="
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
    "
  >
    <text
      style="
        width: 120rpx;
        font-size: 28rpx;
        color: #333;
      "
    >房间名称:</text>
    <view
      style="
        display: flex;
        align-items: center;
        flex: 1;
        height: 70rpx;
        border: 1rpx solid #dcdfe6;
        border-radius: 8rpx;
        padding: 0 20rpx;
        background-color: #f5f7fa;
      "
    >
      <input
        type="text"
        v-model="sendWineForm.roomSearchText"
        placeholder="请输入房间名称搜索"
        @input="handleSendWineRoomSearch"
        style="
          flex: 1;
          height: 100%;
          font-size: 28rpx;
          border: none;
          background-color: transparent;
        "
      />
      <button
        @click="searchSendWineRooms"
        style="
          height: 100%;
          line-height: 70rpx;
          padding: 0 20rpx;
          font-size: 28rpx;
          color: #409eff;
          background-color: transparent;
          border: none;
          border-left: 1rpx solid #dcdfe6;
        "
      >
        搜索
      </button>
    </view>
  </view>

  <!-- 房间选择 -->
  <view
    v-if="filteredRoomList.length > 0"
    style="
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
    "
  >
    <text
      style="
        width: 120rpx;
        font-size: 28rpx;
        color: #333;
      "
    >选择房间:</text>
    <picker
      mode="selector"
      :range="filteredRoomList"
      range-key="cc"
      :value="filteredRoomList.findIndex(item => item.id === sendWineForm.selectedRoomId)"
      @change="handleSendWineRoomChange"
      style="
        flex: 1;
        height: 70rpx;
        border: 1rpx solid #dcdfe6;
        border-radius: 8rpx;
        background-color: #f5f7fa;
      "
    >
      <view
        style="
          height: 70rpx;
          line-height: 70rpx;
          padding: 0 20rpx;
          font-size: 28rpx;
          color: #333;
        "
      >
        {{ sendWineForm.roomName || '请选择房间' }}
      </view>
    </picker>
  </view>

  <!-- 酒名 -->
  <view
    style="
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
    "
  >
    <text
      style="
        width: 120rpx;
        font-size: 28rpx;
        color: #333;
      "
    >酒名:</text>
    <picker
      mode="selector"
      :range="wineOptions"
      :value="wineOptions.indexOf(sendWineForm.wineName)"
      @change="handleSendWineNameChange"
      style="
        flex: 1;
        height: 70rpx;
        border: 1rpx solid #dcdfe6;
        border-radius: 8rpx;
        background-color: #f5f7fa;
      "
    >
      <view
        style="
          height: 70rpx;
          line-height: 70rpx;
          padding: 0 20rpx;
          font-size: 28rpx;
          color: #333;
        "
      >
        {{ sendWineForm.wineName || '请选择酒名' }}
      </view>
    </picker>
  </view>

  <!-- 数量 -->
  <view
    style="
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
    "
  >
    <text
      style="
        width: 120rpx;
        font-size: 28rpx;
        color: #333;
      "
    >数量:</text>
    <input
      type="number"
      v-model="sendWineForm.quantity"
      placeholder="请输入数量"
      style="
        flex: 1;
        height: 70rpx;
        border: 1rpx solid #dcdfe6;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
        background-color: #f5f7fa;
      "
    />
  </view>

  <!-- 确认送酒按钮 -->
  <button
    @click="handleSendWine"
    :disabled="!isSendWineFormValid"
    style="
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      border: none;
      border-radius: 8rpx;
      font-size: 28rpx;
      color: #fff;
      background-color: #409eff;
      transition: background-color 0.2s;
    "
  >
    确认送酒
  </button>
</view>


		<!-- 搜索区域 -->
		<view class="search-section">
			<view class="search-title">查询存酒记录</view>
			<view class="search-item">
				<text class="search-label">房间名称</text>
				<input 
					class="search-input" 
					type="text" 
					v-model="searchForm.roomName" 
					placeholder="请输入房间名称"
				/>
			</view>
			<view class="search-item">
				<text class="search-label">日期</text>
				<picker 
					mode="date" 
					:value="searchForm.date" 
					@change="handleDateChange"
					class="date-picker"
				>
					<view class="picker-text">{{ searchForm.date || '请选择日期' }}</view>
				</picker>
			</view>
			<view class="search-buttons">
				<button class="search-btn" @click="handleSearch">搜索</button>
				<button class="reset-btn" @click="handleReset">重置</button>
			</view>
		</view>

		<view v-if="isBayuan" style="margin-bottom: 20rpx;">
			<view v-for="(wineMap, manager) in groupedWineQuantities" :key="manager" style="background:#fff;border-radius:12rpx;padding:20rpx;margin-bottom:20rpx;box-shadow:0 2rpx 8rpx rgba(0,0,0,0.05);">
				<view style="font-size:30rpx;font-weight:bold;color:#333;margin-bottom:10rpx;">{{ manager }} 存酒总览</view>
				<view v-for="(quantity, wineName) in wineMap" :key="wineName" style="display:flex;justify-content:space-between;padding:10rpx 0;border-bottom:1rpx solid #eee;">
					<text style="font-size:28rpx;color:#666;">{{ wineName }}:</text>
					<text style="font-size:28rpx;color:#007aff;">{{ quantity }} 瓶</text>
				</view>
				<view v-if="Object.keys(wineMap).length === 0" style="text-align:center;color:#999;font-size:28rpx;padding:10rpx 0;">暂无存酒记录</view>
			</view>
		</view>

		<view class="data-list">
			<view class="data-item" v-for="(item, index) in wineList" :key="index">
				<view class="item-header">
					<view class="date">{{ formatDate(item.storageDate) }}</view>
					<view class="room">房间: {{ item.roomName }}</view>
					<view class="manager">业务经理/管理层: {{ item.userName }}</view>
				</view>
				<view class="item-body">
					<view class="info-row">
						<text class="label">酒名:</text>
						<text class="value">{{ item.wineName }}</text>
					</view>
					<view class="info-row">
						<text class="label">数量:</text>
						<text class="value">{{ item.quantity }}</text>
					</view>
					<view class="info-row">
						<text class="label">存酒日期:</text>
						<text class="value">{{ formatDate(item.storageDate) }}</text>
					</view>
					<view class="info-row">
						<text class="label">房间名称:</text>
						<text class="value">{{ item.roomName || item.roomId }}</text>
					</view>
					<view v-if="item.aa === '送酒中'" class="info-row send-status">
						<text class="send-status-text">送酒中</text>
					</view>
					<view v-if="item.bb" class="info-row send-quantity">
						<text class="send-quantity-text">送酒数量: {{ item.bb }} 瓶</text>
					</view>
				</view>
			</view>
			
			<view v-if="loading" class="loading">加载中...</view>
			<view v-else-if="wineList.length === 0" class="no-data">暂无数据</view>
		</view>
	</view>
</template>

<script>
	import { listWine, addWine, updateWine } from '@/api/system/wine'
	import { listUsersByRole } from '@/api/system/user'
	import { getRoom, listRoom } from '@/api/system/room'
	
	export default {
		// 页面配置
		onPullDownRefresh() {
			// 刷新数据
			Promise.all([
				this.isBayuan ? this.getBusinessManagers() : Promise.resolve(),
				this.getWineList()
			]).finally(() => {
				uni.stopPullDownRefresh();
			});
		},
		data() {
			return {
				wineList: [],
				loading: false,
				searchForm: {
					roomName: '',
					date: ''
				},
				originalList: [], // 存储原始数据
				isBayuan: false, // 吧员角色标识
				isBusinessManager: false, // 业务经理/管理层角色标识
				businessManagers: [], // 业务经理/管理层列表
				roomList: [], // 房间列表
				filteredRoomList: [], // 过滤后的房间列表
				showRoomPicker: false, // 是否显示房间选择器
				wineOptions: [
					// 啤酒类
					'1664', '百威铝罐', '青岛铝罐', '科罗娜', '喜力铝罐', '百威听装',
					// 白兰地类
					'至尊', '路易十三', '马爹利尚选', '奥创', '马爹利XO', '人头马XO', '轩尼诗XO', '蓝带马爹利', '马爹利名仕', '轩尼诗VSOP',
					// 威士忌类
					'皇家礼炮', '芝华士12年', '黑方', '杰克丹尼', '麦卡伦12年',
					// 红酒类
					'威龙国际干白', '威龙国际干红', '卡斯特', '威龙有机干红', '威龙有机干白', '青稞干红', '青稞干白', '香槟'
				], // 完整酒名列表
				newWineForm: {
					userId: null,
					userName: '',
					roomId: '',
					roomName: '',
					wineName: '',
					quantity: '',
					selectedRoomId: '', // 新增：选中的房间ID
					roomSearchText: '' // 新增：房间搜索文本
				},
				sendWineForm: { // 业务经理/管理层送酒表单
					roomId: '',
					wineName: '',
					quantity: '',
					roomSearchText: '', // 新增：房间搜索文本
					selectedRoomId: '' // 新增：选中的房间ID
				}
			}
		},
		computed: {
			totalWineQuantities() {
				const quantities = {}
				// 只统计非借酒的记录
				this.wineList
					.filter(item => item.wineName !== '借酒')
					.forEach(item => {
						quantities[item.wineName] = (quantities[item.wineName] || 0) + (parseInt(item.quantity) || 0)
					})
				return quantities
			},
			isNewWineFormValid() {
				return this.newWineForm.userId && 
				       this.newWineForm.roomName && 
				       this.newWineForm.wineName && 
				       this.newWineForm.quantity > 0
			},
			isSendWineFormValid() {
				return this.sendWineForm.roomName && 
				       this.sendWineForm.wineName && 
				       this.sendWineForm.quantity > 0
			},
			groupedWineQuantities() {
				const result = {};
				this.wineList
					.filter(item => item.wineName !== '借酒')
					.forEach(item => {
						if (!result[item.userName]) {
							result[item.userName] = {};
						}
						result[item.userName][item.wineName] = (result[item.userName][item.wineName] || 0) + (parseInt(item.quantity) || 0);
					});
				return result;
			}
		},
		onLoad() {
			const roles = uni.getStorageSync('roles')
			this.isBayuan = roles && roles.includes('bayuan')
			this.isBusinessManager = roles && roles.includes('yewujinli')
			
			if (this.isBayuan) {
				this.getBusinessManagers() // 如果是吧员，获取业务经理/管理层列表
			}
			this.getRoomList() // 获取房间列表
			this.getWineList()
		},
		methods: {
			// 获取业务经理和管理层列表
			async getBusinessManagers() {
				try {
					// 分别获取管理层（角色ID 104）和业务经理（角色ID 105）的人员
					const [managementRes, businessRes] = await Promise.all([
						listUsersByRole(104, null, 1, 1000), // 获取管理层，传递分页参数
						listUsersByRole(105, null, 1, 1000)  // 获取业务经理，传递分页参数
					])
					
					// 合并两个结果
					const managementUsers = managementRes.code === 200 ? (managementRes.rows || []) : []
					const businessUsers = businessRes.code === 200 ? (businessRes.rows || []) : []
					
					// 合并并去重（根据userId去重）
					const allUsers = [...managementUsers, ...businessUsers]
					const uniqueUsers = allUsers.filter((user, index, self) => 
						index === self.findIndex(u => u.userId === user.userId)
					)
					
					this.businessManagers = uniqueUsers
					
					// 检查是否有错误
					if (managementRes.code !== 200) {
						console.error('获取管理层列表失败:', managementRes.msg)
					}
					if (businessRes.code !== 200) {
						console.error('获取业务经理列表失败:', businessRes.msg)
					}
					
				} catch (error) {
					console.error('获取业务经理和管理层列表失败:', error)
					this.$modal.msgError('获取业务经理和管理层列表失败')
				}
			},
			// 处理业务经理/管理层选择
			handleNewWineManagerChange(e) {
				const selectedManager = this.businessManagers[e.detail.value]
				if (selectedManager) {
					this.newWineForm.userId = selectedManager.userId
					this.newWineForm.userName = selectedManager.userName
				}
			},
			// 处理酒名选择
			handleNewWineNameChange(e) {
				this.newWineForm.wineName = this.wineOptions[e.detail.value]
			},
			// 处理酒名选择（送酒）
			handleSendWineNameChange(e) {
				this.sendWineForm.wineName = this.wineOptions[e.detail.value]
			},
			// 处理房间名称选择
			handleRoomNameChange(e) {
				const selectedRoom = this.filteredRoomList[e.detail.value]
				if (selectedRoom) {
					this.newWineForm.roomName = selectedRoom.cc
					this.newWineForm.roomId = selectedRoom.id
					this.newWineForm.selectedRoomId = selectedRoom.id
				}
			},
			// 处理房间搜索输入
			handleRoomSearch() {
				this.searchRooms()
			},
			// 搜索房间
			async searchRooms() {
				const searchText = this.newWineForm.roomSearchText.trim()
				if (!searchText) {
					this.filteredRoomList = this.roomList
					return
				}
				try {
					// 使用模糊搜索，后端会自动添加 % 通配符
					const res = await listRoom({ cc: searchText })
					if (res.code === 200) {
						this.filteredRoomList = res.rows || []
					} else {
						this.filteredRoomList = []
						console.error('搜索房间失败:', res.msg)
					}
				} catch (error) {
					console.error('搜索房间失败:', error)
					this.filteredRoomList = []
				}
			},
			// 处理送酒房间搜索输入
			handleSendWineRoomSearch() {
				this.searchSendWineRooms()
			},
			// 搜索送酒房间
			async searchSendWineRooms() {
				const searchText = this.sendWineForm.roomSearchText.trim()
				if (!searchText) {
					this.filteredRoomList = this.roomList
					return
				}
				try {
					// 使用模糊搜索，后端会自动添加 % 通配符
					const res = await listRoom({ cc: searchText })
					if (res.code === 200) {
						this.filteredRoomList = res.rows || []
					} else {
						this.filteredRoomList = []
						console.error('搜索房间失败:', res.msg)
					}
				} catch (error) {
					console.error('搜索房间失败:', error)
					this.filteredRoomList = []
				}
			},
			// 处理送酒房间选择
			handleSendWineRoomChange(e) {
				const selectedRoom = this.filteredRoomList[e.detail.value]
				if (selectedRoom) {
					this.sendWineForm.roomName = selectedRoom.cc
					this.sendWineForm.roomId = selectedRoom.id
					this.sendWineForm.selectedRoomId = selectedRoom.id
				}
			},
			// 处理新增存酒
			async handleAddWine() {
				if (!this.isNewWineFormValid) {
					this.$modal.msgError('请填写所有必填项并确保数量大于0')
					return
				}
				
				try {
					const userInfo = uni.getStorageSync('userInfo')
					if (!userInfo || !userInfo.user) {
						throw new Error('未获取到当前用户信息')
					}

					// 如果当前用户是"吧员"，则先查询该房间下是否已有该酒名的记录
					if (this.isBayuan) {
						// 构造查询参数，查询该房间（roomId）下酒名为 newWineForm.wineName 且 userId 为 newWineForm.userId 的记录
						const query = { roomId: this.newWineForm.roomId, wineName: this.newWineForm.wineName, userId: this.newWineForm.userId }
						const res = await listWine(query)
						if (res.code === 200 && res.rows && res.rows.length > 0) {
							// 已有记录，则更新该记录（取第一条，假设唯一）
							const oldRecord = res.rows[0]
							const newQuantity = oldRecord.quantity + parseInt(this.newWineForm.quantity)
							const updateData = { ...oldRecord, quantity: newQuantity }
							const updateRes = await updateWine(updateData)
							if (updateRes.code === 200) {
								this.$modal.msgSuccess('更新存酒记录成功')
							} else {
								this.$modal.msgError(updateRes.msg || '更新存酒记录失败')
							}
						} else {
							// 无记录，则新增一条
							const dataToSubmit = {
								userId: this.newWineForm.userId,
								userName: this.newWineForm.userName,
								roomId: this.newWineForm.roomId,
								roomName: this.newWineForm.roomName,
								wineName: this.newWineForm.wineName,
								quantity: parseInt(this.newWineForm.quantity),
								// 存酒日期默认为当前日期
								storageDate: new Date().toISOString().split('T')[0] + ' ' + new Date().toTimeString().split(' ')[0]
							}
							const addRes = await addWine(dataToSubmit)
							if (addRes.code === 200) {
								this.$modal.msgSuccess('新增存酒记录成功')
							} else {
								this.$modal.msgError(addRes.msg || '新增存酒记录失败')
							}
						}
					} else {
						// 非吧员（例如业务经理/管理层）则直接新增
						const dataToSubmit = {
							userId: this.newWineForm.userId,
							userName: this.newWineForm.userName,
							roomId: this.newWineForm.roomId,
							roomName: this.newWineForm.roomName,
							wineName: this.newWineForm.wineName,
							quantity: parseInt(this.newWineForm.quantity),
							// 存酒日期默认为当前日期
							storageDate: new Date().toISOString().split('T')[0] + ' ' + new Date().toTimeString().split(' ')[0]
						}
						const addRes = await addWine(dataToSubmit)
						if (addRes.code === 200) {
							this.$modal.msgSuccess('新增存酒记录成功')
						} else {
							this.$modal.msgError(addRes.msg || '新增存酒记录失败')
						}
					}
					// 清空表单
					this.newWineForm = {
						userId: null,
						userName: '',
						roomId: '',
						roomName: '',
						wineName: '',
						quantity: '',
						selectedRoomId: '',
						roomSearchText: ''
					}
					// 刷新存酒列表
					this.getWineList()
				} catch (error) {
					console.error('新增或更新存酒记录失败:', error)
					this.$modal.msgError(error.message || '新增或更新存酒记录失败')
				}
			},
			// 处理业务经理/管理层送酒
			async handleSendWine() {
				if (!this.isSendWineFormValid) {
					this.$modal.msgError('请填写所有必填项并确保数量大于0')
					return
				}
				
				try {
					// 获取当前登录用户信息
					const userInfo = uni.getStorageSync('userInfo')
					let queryUserName = this.sendWineForm.userName
					let queryUserId = this.sendWineForm.userId
					if (this.isBusinessManager && userInfo && userInfo.user) {
						queryUserName = userInfo.user.userName
						queryUserId = userInfo.user.userId
					}
					// 构造查询参数，查询该房间（sendWineForm.roomId）下酒名为 sendWineForm.wineName 且 userName 和 userId 匹配的记录
					const query = { roomId: this.sendWineForm.roomId, wineName: this.sendWineForm.wineName, userName: queryUserName, userId: queryUserId }
					const res = await listWine(query)
					if (res.code === 200 && res.rows && res.rows.length > 0) {
						// 取第一条记录（假设唯一）
						const oldRecord = res.rows[0]
						const oldQuantity = oldRecord.quantity
						const sendQuantity = parseInt(this.sendWineForm.quantity)
						if (oldQuantity < sendQuantity) {
							this.$modal.msgError('数量不足，现有数量为' + oldQuantity + '瓶')
							return
						}
						// 计算新的送酒总数（bb）：如果之前有送酒记录则累加，否则使用当前送酒数量
						const previousSendQuantity = oldRecord.bb ? parseInt(oldRecord.bb) : 0
						const newTotalSendQuantity = previousSendQuantity + sendQuantity
						// 更新 aa 字段为"送酒中"，bb 字段为累计送酒数量，并更新 quantity 字段
						const updateData = { 
							...oldRecord, 
							aa: '送酒中', 
							bb: newTotalSendQuantity, 
							quantity: oldQuantity - sendQuantity 
						}
						const updateRes = await updateWine(updateData)
						if (updateRes.code === 200) {
							this.$modal.msgSuccess('送酒状态更新成功')
							// 更新 wineList 中对应记录
							const index = this.wineList.findIndex(item => item.id === oldRecord.id)
							if (index !== -1) {
								this.wineList[index] = { 
									...this.wineList[index], 
									aa: '送酒中', 
									bb: newTotalSendQuantity, 
									quantity: oldQuantity - sendQuantity 
								}
							}
						} else {
							this.$modal.msgError(updateRes.msg || '送酒状态更新失败')
						}
					} else {
						this.$modal.msgError('未找到该房间下该酒名的存酒记录')
					}
					// 清空送酒表单
					this.sendWineForm = { 
						roomId: '', 
						roomName: '', 
						wineName: '', 
						quantity: '', 
						roomSearchText: '', 
						selectedRoomId: '' 
					}
				} catch (error) {
					console.error('送酒状态更新失败:', error)
					this.$modal.msgError(error.message || '送酒状态更新失败')
				}
			},
			// 获取房间列表
			async getRoomList() {
				try {
					const res = await listRoom()
					if (res.code === 200) {
						this.roomList = res.rows || []
						this.filteredRoomList = this.roomList // 初始化时也显示所有房间
					} else {
						console.error('获取房间列表失败:', res.msg)
					}
				} catch (error) {
					console.error('获取房间列表失败:', error)
				}
			},
			// 获取存酒列表
			async getWineList() {
				this.loading = true
				try {
					const userInfo = uni.getStorageSync('userInfo')
					if (!userInfo || !userInfo.user) {
						this.$modal.msgError('未获取到用户信息')
						this.loading = false
						return
					}

					let queryParams = {};
					// 如果是吧员，不带userId查询所有；否则带userId查询自己的
					if (!this.isBayuan) {
						queryParams.userId = userInfo.user.userId;
					}

					const res = await listWine(queryParams)
						if (res.code === 200) {
							this.originalList = res.rows || []
							this.filterList()
						} else {
							this.$modal.msgError(res.msg || '获取数据失败')
					}
				} catch (error) {
					console.error('获取存酒列表失败:', error)
					this.$modal.msgError('获取数据失败')
				} finally {
					this.loading = false
				}
			},
			// 处理日期选择
			handleDateChange(e) {
				this.searchForm.date = e.detail.value
			},
			// 处理搜索
			handleSearch() {
				this.filterList()
			},
			// 处理重置
			handleReset() {
				this.searchForm = {
					roomName: '',
					date: ''
				}
				this.wineList = [...this.originalList]
			},
			// 过滤列表
			filterList() {
				let filteredList = [...this.originalList]
				
				// 过滤掉借酒记录（wineName为'借酒'的记录）
				filteredList = filteredList.filter(item => item.wineName !== '借酒')
				
				// 按房间名称筛选
				if (this.searchForm.roomName) {
					filteredList = filteredList.filter(item => 
						item.roomName && item.roomName.includes(this.searchForm.roomName)
					)
				}
				
				// 按日期筛选
				if (this.searchForm.date) {
					filteredList = filteredList.filter(item => {
						const itemDate = this.formatDate(item.storageDate)
						return itemDate === this.searchForm.date
					})
				}
				
				// 按日期降序排序
				filteredList.sort((a, b) => new Date(b.storageDate) - new Date(a.storageDate));
				this.wineList = filteredList
			},
			formatDate(dateStr) {
				if (!dateStr) return '暂无'
				const date = new Date(dateStr)
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
			}
		}
	}
</script>

<style lang="scss" scoped>
.cunjiu-container {
	padding: 20rpx;
	background-color: #f5f7fa;
	min-height: 100vh;
}

.search-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

	.search-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		margin-bottom: 20rpx;
	}

	.search-item {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		&:last-child {
			margin-bottom: 0;
		}

		.search-label {
			width: 120rpx;
			font-size: 28rpx;
			color: #333;
		}

		.search-input {
			flex: 1;
			height: 70rpx;
			border: 1rpx solid #dcdfe6;
			border-radius: 8rpx;
			padding: 0 20rpx;
			font-size: 28rpx;
			background-color: #f5f7fa;
		}

		.date-picker {
			flex: 1;
			height: 70rpx;
			border: 1rpx solid #dcdfe6;
			border-radius: 8rpx;
			background-color: #f5f7fa;

			.picker-text {
				height: 70rpx;
				line-height: 70rpx;
				padding: 0 20rpx;
				font-size: 28rpx;
				color: #333;
			}
		}
	}

	.search-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 20rpx;
		gap: 20rpx;

		.search-btn, .reset-btn {
			flex: 1;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-radius: 8rpx;
			font-size: 28rpx;
			border: none;
		}

		.search-btn {
			background-color: #409eff;
			color: #fff;

			&:active {
				background-color: #3a8ee6;
			}
		}

		.reset-btn {
			background-color: #f5f7fa;
			color: #606266;
			border: 1rpx solid #dcdfe6;

			&:active {
				background-color: #e6e8eb;
			}
		}
	}
}

.data-list {
	/* 列表容器样式 */
}

.data-item {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #eee;
		padding-bottom: 20rpx;
		margin-bottom: 20rpx;

		.date {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.room {
			font-size: 28rpx;
			color: #666;
		}
	}

	.item-body {
		.info-row {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.label {
				font-size: 28rpx;
				color: #555;
				flex-basis: 150rpx;
				margin-right: 20rpx;
			}

			.value {
				font-size: 28rpx;
				color: #333;
				flex: 1;
				text-align: right;
			}
		}
	}
}

.loading, .no-data {
	text-align: center;
	padding: 30rpx;
	color: #999;
	font-size: 28rpx;
}

.add-wine-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

	.section-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 25rpx;

		.label {
			width: 160rpx;
			font-size: 30rpx;
			color: #555;
			flex-shrink: 0;
		}

		.input, .picker {
			flex: 1;
			height: 80rpx;
			border: 1rpx solid #dcdfe6;
			border-radius: 8rpx;
			padding: 0 20rpx;
			font-size: 30rpx;
			background-color: #f5f7fa;
			box-sizing: border-box;
		}

		.picker-text {
			height: 80rpx;
			line-height: 80rpx;
			color: #333;
		}

		.room-search-container {
			display: flex;
			align-items: center;
			flex: 1;
			height: 80rpx;
			border: 1rpx solid #dcdfe6;
			border-radius: 8rpx;
			padding: 0 20rpx;
			background-color: #f5f7fa;

			.room-search-input {
				flex: 1;
				height: 100%;
				font-size: 28rpx;
				border: none;
				background-color: transparent;
			}

			.room-search-btn {
				height: 100%;
				line-height: 80rpx;
				padding: 0 20rpx;
				font-size: 28rpx;
				color: #409eff;
				background-color: transparent;
				border: none;
				border-left: 1rpx solid #dcdfe6;
			}
		}
	}

	.confirm-add-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #409eff;
		color: #fff;
		border-radius: 45rpx;
		font-size: 36rpx;
		margin-top: 40rpx;
		border: none;

		&:disabled {
			background-color: #a0cfff;
			cursor: not-allowed;
		}
	}

	.total-quantities-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.total-quantities-section .section-title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		color: #333;
		text-align: center;
	}

	.total-item {
		display: flex;
		justify-content: space-between;
		padding: 15rpx 0;
	}

	.total-item:last-child {
		border-bottom: none;
	}

	.total-item .wine-name {
		font-size: 30rpx;
		color: #666;
		font-weight: bold;
	}

	.total-item .total-quantity {
		font-size: 30rpx;
		font-weight: bold;
		color: #007aff;
	}

	.no-totals {
		text-align: center;
		color: #999;
		font-size: 28rpx;
		padding: 20rpx 0;
	}

	.search-section {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.send-wine-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.send-wine-section .section-title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		color: #333;
		text-align: center;
	}

	.send-wine-section .form-item {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.send-wine-section .label {
		width: 180rpx;
		font-size: 30rpx;
		color: #666;
	}

	.send-wine-section .input, .send-wine-section .picker {
		flex: 1;
		height: 80rpx;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 30rpx;
	}

	.send-wine-section .picker-text {
		line-height: 80rpx;
	}

	.send-wine-section .confirm-send-btn {
		margin-top: 30rpx;
		background-color: #007aff;
		color: white;
		border-radius: 10rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 30rpx;
		transition: background-color 0.3s;
		&:hover { background-color: #005bb5; }
	}

	.send-wine-section .confirm-send-btn[disabled] {
		background-color: #a0cfff;
	}

	.send-status, .send-quantity {
		margin-top: 10rpx;
		background-color: #f0f0f0;
		padding: 5rpx 10rpx;
		border-radius: 5rpx;
		display: inline-block;
	}
	.send-status-text {
		color: #ff6b6b;
		font-weight: bold;
	}
	.send-quantity-text {
		color: #666;
		font-weight: bold;
	}
}
</style>
